package com.practice.flty;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class PLInfo {
    private static final Logger logger = LoggerFactory.getLogger(PLInfo.class);

    public static void main(String[] args) throws Exception {
        rQPeiLv();

    }

    //胜平负数据
    public static JSONArray rQPeiLv() {
        String xmlContent = fetchXMLContent("https://trade.500.com/static/public/jczq/newxml/pl/pl_spf_2.xml");
        return convertXmlToJson(xmlContent);

    }

        //让球数据
    public JSONArray  sFPeiLv() {
        String xmlContent = fetchXMLContent("https://trade.500.com/static/public/jczq/newxml/pl/pl_nspf_2.xml");
        return convertXmlToJson(xmlContent);

    }

    public static void getBiFenPeiLv() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 格式化当前时间
        String formattedDate = now.format(formatter);

        String urlString = "https://trade.500.com/jczq/?playid=271&g=2&date=" + formattedDate;
        String res = fetchXMLContent(urlString);
        org.jsoup.nodes.Document doc = Jsoup.parse(res);
        org.jsoup.nodes.Element elementsWithClass =  doc.getElementById("relativeContainer");
        org.jsoup.select.Elements  elements = elementsWithClass.getElementsByClass("bet-main-dg");
        org.jsoup.nodes.Element betMainDg = elements.get(0);
        //TODO 需要进一步拆分
        org.jsoup.select.Elements  bfInfoElements = betMainDg.getElementsByClass("bet-tb-dg");
        org.jsoup.select.Elements bsElements = bfInfoElements.get(1).getElementsByClass("bet-tb-tr");
        org.jsoup.select.Elements bfPlElements = bfInfoElements.get(1).getElementsByClass("bet-more-wrap");



        System.out.println(res);


    }


 /*   public JSONObject convertBifen(org.jsoup.nodes.Element element) {
        JSONObject jsonObject = new JSONObject();
        element.attr("")


    }*/



    public static String fetchXMLContent(String urlString) {
        NoopHostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLHostnameVerifier(hostnameVerifier)
                .build();

        HttpGet httpGet = new HttpGet(urlString);

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode < 300) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, "utf-8");
                } else {
                    logger.warn("Response contains no entity.");
                }
            } else {
                logger.warn("Unexpected response status code: {}", statusCode);
            }
        } catch (Exception e) {
            logger.error("An error occurred while fetching XML content from URL: {}", urlString, e);
        }
        return null;
    }


    public static JSONArray convertXmlToJson(String xmlData) {
        JSONArray jsonArray = new JSONArray();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new ByteArrayInputStream(xmlData.getBytes(StandardCharsets.UTF_8)));
            NodeList mElements = document.getElementsByTagName("m");

            for (int i = 0; i < mElements.getLength(); i++) {
                Element mElement = (Element) mElements.item(i);
                jsonArray.add(constructMatchJson(mElement));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonArray;
    }

    private static JSONObject constructMatchJson(Element mElement) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", mElement.getAttribute("id"));
        jsonObject.put("date", mElement.getAttribute("date"));
        jsonObject.put("dayofweek", mElement.getAttribute("dayofweek"));
        jsonObject.put("matchnum", mElement.getAttribute("matchnum"));
        jsonObject.put("league", mElement.getAttribute("league"));
        jsonObject.put("home", mElement.getAttribute("home"));
        jsonObject.put("away", mElement.getAttribute("away"));
        JSONArray rowsArray = new JSONArray();

        NodeList rowElements = mElement.getElementsByTagName("row");
        for (int j = 0; j < rowElements.getLength(); j++) {
            Element rowElement = (Element) rowElements.item(j);
            JSONObject rowObject = new JSONObject();
            rowObject.put("win", rowElement.getAttribute("win"));
            rowObject.put("draw", rowElement.getAttribute("draw"));
            rowObject.put("lost", rowElement.getAttribute("lost"));
            rowObject.put("w", rowElement.getAttribute("w"));
            rowObject.put("d", rowElement.getAttribute("d"));
            rowObject.put("l", rowElement.getAttribute("l"));
            rowObject.put("poolid", rowElement.getAttribute("poolid"));
            rowObject.put("time", rowElement.getAttribute("time"));
            rowObject.put("updatetime", rowElement.getAttribute("updatetime"));
            rowsArray.add(rowObject);
        }

        jsonObject.put("rows", rowsArray);
        return jsonObject;
    }


}
